'''
Created on 04/03/2009

@author: eh01
'''
from domain.node import Node
from daohelper import DAOHelper
from google.appengine.api import memcache
import logging
import datetime

class NodeDAO(DAOHelper):
    
    node_prefix = 'node_'

    def getCurrentlyConnectedNodes(self):
        """ returns all currently connected nodes. This includes all nodes that have 
            attempted to connect to the hub in the last 30 minutes """
        thirty_mins = datetime.timedelta(minutes=30)
        date_time_now = datetime.datetime.now()
        date_time_thirty_mins_ago = date_time_now - thirty_mins
        query = Node.all()
        query.filter("timestamp > ", date_time_thirty_mins_ago)
        nodes = self.copyQueryResultsToList(query)
        return nodes
    
    def getAllNodes(self):
        query = Node.all()
        nodes = self.copyQueryResultsToList(query)
        return nodes
    
    def findByNodeId(self, id):
        node = memcache.get(self.node_prefix + id)
        if node:
            logging.info('Found node ' + id + ' in memcache')
            return node
        else:
            query = Node.gql("WHERE id = " + id)
            node = self.copyQueryResultsToList(query.fetch(1))
            if node:
                logging.info('Found node ' + id + ' in datastore')
                return node[0]
        return None
            
    
    def save(self, node):
        node.timestamp = datetime.datetime.now()
        node.put()
        logging.info('Add node ' + str(node.id) + ' to memcache')
        memcache.set(self.node_prefix + str(node.id), node)